package org.example.judge;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class MyUtils {
    /**
     * 将字段名转换为数据库字段名 ，驼峰转换为下划线的命名方式
     *
     * @param field
     * @return
     */
    public static String setFieldName(String field) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < field.length(); i++) {
            char c = field.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                str.append('_');
                c = (char) (c - 'A' + 'a');
            }
            str.append(c);
        }
        return str.toString();
    }

    // 判断字符串是否为空
    public static boolean isEmpty(String s) {
        return s == null || "".equals(s);
    }

    /**
     * 从请求中获取登录者的登录校验信息
     *
     * @param request
     * @return
     */
    public static String getLoginCookie(HttpServletRequest request) {
        if (request.getCookies() == null) return null;
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("token")) {  //找到登录token
                return cookie.getValue();
            }
        }
        return null;
    }

    public static boolean isNotEmpty(String field) {
        return !isEmpty(field);
    }
}
